<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="nickName">
        <el-input
            v-model="queryParams.nickName"
            placeholder="请输入用户名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="年龄" prop="userAge">
        <el-input
            v-model="queryParams.userAge"
            placeholder="请输入年龄"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="医生科属" style="width: 250px" prop="departmentName">
        <el-select
            v-model="queryParams.departmentName"
            placeholder="请选择医生科属"
            clearable
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="dept in departmentList"
              :key="dept.departmentTypeId"
              :label="dept.departmentName"
              :value="dept.departmentName"
          />
        </el-select>
      </el-form-item>

      <!-- 修改：将团队输入框改为下拉框 -->
      <el-form-item label="团队名称" style="width: 250px" prop="teamName">
        <el-select
            v-model="queryParams.teamName"
            placeholder="请选择团队名称"
            clearable
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="team in teamList"
              :key="team.teamId"
              :label="team.teamName"
              :value="team.teamName"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="primary"-->
<!--            plain-->
<!--            icon="Plus"-->
<!--            @click="handleAdd"-->
<!--            v-hasPermi="['behindDoctor:yyybehinddoctor:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['behindDoctor:yyybehinddoctor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['behindDoctor:yyybehinddoctor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['behindDoctor:yyybehinddoctor:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="yyybehinddoctorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="医生名称" align="center" prop="nickName" />
      <el-table-column label="手机号码" align="center" prop="phonenumber" />
      <el-table-column label="用户性别" align="center">
        <template #default="scope">
          <el-tag
              :type="scope.row.sex === '0' ? 'primary' : 'success'"
              size="small"
          >
            {{ scope.row.sex === '0' ? '男' : (scope.row.sex === '1' ? '女' : '未知') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="userAge" />
      <el-table-column label="医生科属" align="center" prop="departmentName" />
      <el-table-column label="团队名称" align="center" prop="teamName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['behindDoctor:yyybehinddoctor:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['behindDoctor:yyybehinddoctor:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改所有医生对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="yyybehinddoctorRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="年龄" prop="userAge">
          <el-input v-model="form.userAge" placeholder="请输入年龄" type="number" />
        </el-form-item>
        <el-form-item label="医生科属" prop="departmentTypeId">
          <el-select
              v-model="form.departmentTypeId"
              placeholder="请选择医生科属"
              clearable
          >
            <el-option
                v-for="dept in departmentList"
                :key="dept.departmentTypeId"
                :label="dept.departmentName"
                :value="dept.departmentTypeId"
            />
          </el-select>
        </el-form-item>
        <!-- 修改：将团队ID输入框改为下拉框 -->
        <el-form-item label="团队名称" prop="teamId">
          <el-select
              v-model="form.teamId"
              placeholder="请选择团队"
              clearable
          >
            <el-option
                v-for="team in teamList"
                :key="team.teamId"
                :label="team.teamName"
                :value="team.teamId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Yyybehinddoctor">
import { listYyybehinddoctor, getYyybehinddoctor, delYyybehinddoctor, addYyybehinddoctor, updateYyybehinddoctor } from "@/api/behindDoctor/yyybehinddoctor"
import { listAllDepartments } from "@/api/behindDoctor/department"
// 新增：导入团队相关API
import { getAllTeams } from "@/api/behindDoctor/team"
import { getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()

// 科室列表
const departmentList = ref([])
// 新增：团队列表
const teamList = ref([])
// 医生列表
const yyybehinddoctorList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
    userId: null,
    nickName: null,
    phonenumber: null,
    userAge: null,
    departmentTypeId: null,
    teamId: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: null,
    userAge: null,
    departmentName: null,
    teamName: null,
  },
  rules: {
    nickName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" }
    ],
    phonenumber: [
      { required: true, message: "手机号码不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    departmentTypeId: [
      { required: true, message: "医生科属不能为空", trigger: "change" }
    ],
    // 新增：团队必填验证
    teamId: [
      { required: true, message: "团队不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询所有医生列表 */
function getList() {
  loading.value = true
  listYyybehinddoctor(queryParams.value).then(response => {
    yyybehinddoctorList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(error => {
    console.error('获取医生列表失败', error)
    loading.value = false
  })
}

/** 获取科室列表 */
function getDepartmentList() {
  listAllDepartments().then(response => {
    departmentList.value = response.data || []
  }).catch(error => {
    console.error('获取科室列表失败', error)
  })
}

// 新增：获取团队列表
function getTeamList() {
  getAllTeams().then(response => {
    teamList.value = response.data || []
  }).catch(error => {
    console.error('获取团队列表失败', error)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    nickName: null,
    phonenumber: null,
    userAge: null,
    departmentTypeId: null,
    teamId: null
  }
  if (proxy && proxy.resetForm) {
    proxy.resetForm("yyybehinddoctorRef")
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  if (proxy && proxy.resetForm) {
    proxy.resetForm("queryRef")
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length !== 1
  multiple.value = selection.length === 0
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加医生"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _userId = row ? row.userId : (ids.value.length > 0 ? ids.value[0] : null)
  if (!_userId) {
    proxy.$modal.msgWarning("请选择一条数据进行修改")
    return
  }

  getYyybehinddoctor(_userId).then(response => {
    form.value = { ...response.data }
    open.value = true
    title.value = "修改医生"
  }).catch(error => {
    console.error('获取医生详情失败', error)
    proxy.$modal.msgError("获取数据失败")
  })
}

/** 提交按钮 */
function submitForm() {
  if (!proxy.$refs["yyybehinddoctorRef"]) return

  proxy.$refs["yyybehinddoctorRef"].validate(valid => {
    if (valid) {
      const submitFunc = form.value.userId ? updateYyybehinddoctor : addYyybehinddoctor

      submitFunc(form.value).then(response => {
        proxy.$modal.msgSuccess(form.value.userId ? "修改成功" : "新增成功")
        open.value = false
        getList()
      }).catch(error => {
        console.error('提交失败', error)
        proxy.$modal.msgError("操作失败")
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _userIds = row ? [row.userId] : ids.value
  if (_userIds.length === 0) {
    proxy.$modal.msgWarning("请选择数据进行删除")
    return
  }

  proxy.$modal.confirm(`是否确认删除选中的${_userIds.length}条医生数据？`).then(() => {
    return delYyybehinddoctor(_userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  if (proxy && proxy.download) {
    proxy.download('behindDoctor/yyybehinddoctor/export', {
      ...queryParams.value
    }, `yyybehinddoctor_${new Date().getTime()}.xlsx`)
  }
}

// 初始化加载数据
getDepartmentList()
// 新增：初始化加载团队列表
getTeamList()
getList()
</script>
